﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace GONES.Tools.Common
{
    #region 图片防缩
    /// <summary>
    /// 图片处理类
    /// 1、生成缩略图片或按照比例改变图片的大小和画质
    /// 2、将生成的缩略图放到指定的目录下
    /// </summary>
    public class ImageScale
    {
        public Image ResourceImage;
        private int ImageWidth;
        private int ImageHeight;

        public string ErrMessage;

        public bool IsNoSmallCheck
        {
            get;
            set;
        }

        /// <summary>
        /// 类的构造函数
        /// </summary>
        /// <param name="ImageFileName">图片文件的全路径名称</param>
        public ImageScale(string ImageFileName)
        {
            ResourceImage = Image.FromFile(ImageFileName);

            ErrMessage = "";
        }

        public ImageScale(Stream streamImage)
        {
            ResourceImage = Image.FromStream(streamImage);
            ErrMessage = "";
        }

        public ImageScale(string ImageFileName, bool isnocheck)
        {
            ResourceImage = Image.FromFile(ImageFileName);
            IsNoSmallCheck = isnocheck;

            ErrMessage = "";
        }

        public ImageScale(Stream streamImage, bool isnocheck)
        {
            ResourceImage = Image.FromStream(streamImage);
            IsNoSmallCheck = isnocheck;
            ErrMessage = "";
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 生成缩略图重载方法1，返回缩略图的Image对象
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <returns>缩略图的Image对象</returns>
        public Image GetReducedImage(int Width, int Height)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

        /// <summary>
        /// 生成缩略图重载方法2，将缩略图文件保存到指定的路径
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <param name="targetFilePath">缩略图保存的全文件名，(带路径)，参数格式：D:\Images\filename.jpg</param>
        /// <returns>成功返回true，否则返回false</returns>
        public bool GetReducedImage(int Width, int Height, string targetFilePath)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 生成缩略图重载方法2，将缩略图文件保存到指定的路径
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <param name="targetFilePath">缩略图保存的全文件名，(带路径)，参数格式：D:\Images\filename.jpg</param>
        /// <returns>成功返回true，否则返回false</returns>
        public bool GetReducedImage(int Width, string targetFilePath)
        {
            int Height;
            ImageWidth = Convert.ToInt32(ResourceImage.Width);
            ImageHeight = Convert.ToInt32(ResourceImage.Height);
            if (IsNoSmallCheck)
            {
                if (ResourceImage.Width < Width)
                {
                    Width = ImageWidth;
                    Height = ImageHeight;
                }
                else
                {
                    Height = ImageHeight * Width / ImageWidth;
                }
            }
            else
            {
                Height = ImageHeight * Width / ImageWidth;
            }


            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 生成缩略图重载方法3，返回缩略图的Image对象
        /// </summary>
        /// <param name="Percent">缩略图的宽度百分比如：需要百分之80，就填0.8</param> 
        /// <returns>缩略图的Image对象</returns>
        public Image GetReducedImage(double Percent)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Height * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                return ReducedImage;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return null;
            }
        }

        /// <summary>
        /// 生成缩略图重载方法4，返回缩略图的Image对象
        /// </summary>
        /// <param name="Percent">缩略图的宽度百分比如：需要百分之80，就填0.8</param> 
        /// <param name="targetFilePath">缩略图保存的全文件名，(带路径)，参数格式：D:\Images\filename.jpg</param>
        /// <returns>成功返回true,否则返回false</returns>
        public bool GetReducedImage(double Percent, string targetFilePath)
        {
            try
            {
                Image ReducedImage;

                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);

                ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
                ImageHeight = Convert.ToInt32(ResourceImage.Width * Percent);

                ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);

                ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);

                ReducedImage.Dispose();

                return true;
            }
            catch (Exception e)
            {
                ErrMessage = e.Message;
                return false;
            }
        }
    }
    #endregion

    #region 图片印章
    public class TextOnSeal
    {
        private string _text;
        private Font _font;
        private Color _pathcolor = Color.Red;
        private Color _color = Color.Black;
        private Color _fillcolor = Color.Black;
        private int _letterspace = 10;
        private bool _showpath = true;
        private Rectangle _rectcircle;
        private Rectangle _rect;
        private int _intentlength = 10;
        private Char_Direction _chardirect = Char_Direction.Center;
        private int _degree = 90;
        private string _basestring;

        #region Class_Properties

        public Char_Direction CharDirection
        {
            get { return _chardirect; }
            set
            {
                if (_chardirect != value)
                {
                    _chardirect = value;
                    switch (_chardirect)
                    {
                        case Char_Direction.Center:
                            _degree = 90;
                            break;
                        case Char_Direction.ClockWise:
                            _degree = 0;
                            break;
                        case Char_Direction.OutSide:
                            _degree = -90;
                            break;
                        case Char_Direction.AntiClockWise:
                            _degree = 180;
                            break;
                    }
                }
            }
        }

        public string BaseString
        {
            get { return _basestring; }
            set { _basestring = value; }
        }

        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        public Font TextFont
        {
            get { return _font; }
            set { _font = value; }
        }

        public Color PathColor
        {
            get { return _pathcolor; }
            set { _pathcolor = value; }
        }

        public Color ColorTOP
        {
            get { return _color; }
            set { _color = value; }
        }

        public Color FillColor
        {
            get { return _fillcolor; }
            set { _fillcolor = value; }
        }

        public int LetterSpace
        {
            get { return _letterspace; }
            set { _letterspace = value; }
        }

        public bool ShowPath
        {
            get { return _showpath; }
            set { _showpath = value; }
        }

        public int SealSize
        {
            set
            {
                _rect = new Rectangle(0, 0, value, value);
                _rectcircle = new Rectangle(new Point(_rect.X + _intentlength, _rect.Y + _intentlength), new Size(_rect.Width - 2 * _intentlength, _rect.Height - 2 * _intentlength));
            }
        }

        #endregion {Class_Properties}

        public void SetIndent(int IntentLength)
        {
            _intentlength = IntentLength;
            _rectcircle = new Rectangle(_intentlength, _intentlength, _rect.Width - _intentlength * 2, _rect.Height - _intentlength * 2);
        }

        public TextOnSeal()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public Bitmap TextOnPathBitmap(
            Rectangle rectCircle,
            string strText,
            Font fntText,
            Color clrColor,
            Color clrFill,
            int nPercentage)
        {
            _rect = rectCircle;
            _rectcircle = new Rectangle(new Point(_rect.X + _intentlength, _rect.Y + _intentlength), new Size(_rect.Width - 2 * _intentlength, _rect.Height - 2 * _intentlength));
            _text = strText;
            _font = fntText;
            _color = clrColor;
            _fillcolor = clrFill;
            _letterspace = nPercentage;
            return TextOnPathBitmap();
        }

        /// <summary>
        /// Compute string total length and every char length
        /// </summary>
        /// <param name="sText"></param>
        /// <param name="g"></param>
        /// <param name="fCharWidth"></param>
        /// <param name="fIntervalWidth"></param>
        /// <returns></returns>

        private float ComputeStringLength(string sText, Graphics g, float[] fCharWidth,
            float fIntervalWidth,
            Char_Direction Direction)
        {

            // Init string format
            StringFormat sf = new StringFormat();
            sf.Trimming = StringTrimming.None;
            sf.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;

            // Measure whole string length
            SizeF size = g.MeasureString(sText, _font, (int)_font.Style);
            RectangleF rect = new RectangleF(0f, 0f, size.Width, size.Height);

            // Measure every character size
            CharacterRange[] crs = new CharacterRange[sText.Length];
            for (int i = 0; i < sText.Length; i++)
                crs[i] = new CharacterRange(i, 1);

            // Reset string format
            sf.FormatFlags = StringFormatFlags.NoClip;
            sf.SetMeasurableCharacterRanges(crs);
            sf.Alignment = StringAlignment.Near;

            // Get every character size
            Region[] regs = g.MeasureCharacterRanges(sText, _font, rect, sf);

            // Re-compute whole string length with space interval width
            float fTotalWidth = 0f;
            for (int i = 0; i < regs.Length; i++)
            {
                if (Direction == Char_Direction.Center || Direction == Char_Direction.OutSide)
                    fCharWidth[i] = regs[i].GetBounds(g).Width;
                else
                    fCharWidth[i] = regs[i].GetBounds(g).Height;
                fTotalWidth += fCharWidth[i] + fIntervalWidth;

            }
            fTotalWidth -= fIntervalWidth;//Remove the last interval width
            return fTotalWidth;
        }

        /// <summary>
        /// Compute every char position
        /// </summary>
        /// <param name="CharWidth"></param>
        /// <param name="recChars"></param>
        /// <param name="CharAngle"></param>
        /// <param name="StartAngle"></param>
        private void ComputeCharPos(
            float[] CharWidth,
            PointF[] recChars,
            double[] CharAngle,
            double StartAngle)
        {
            double fSweepAngle, fCircleLength;

            //Compute the circumference
            fCircleLength = _rectcircle.Width * Math.PI;
            for (int i = 0; i < CharWidth.Length; i++)
            {
                //Get char sweep angle
                fSweepAngle = CharWidth[i] * 360 / fCircleLength;

                //Set point angle
                CharAngle[i] = StartAngle + fSweepAngle / 2;

                //Get char position
                if (CharAngle[i] < 270f)
                    recChars[i] = new PointF(_rectcircle.X + _rectcircle.Width / 2 - (float)(_rectcircle.Width / 2 * Math.Sin(Math.Abs(CharAngle[i] - 270) * Math.PI / 180)), _rectcircle.Y + _rectcircle.Width / 2 - (float)(_rectcircle.Width / 2 * Math.Cos(Math.Abs(CharAngle[i] - 270) * Math.PI / 180)));
                else
                    recChars[i] = new PointF(_rectcircle.X + _rectcircle.Width / 2 + (float)(_rectcircle.Width / 2 * Math.Sin(Math.Abs(CharAngle[i] - 270) * Math.PI / 180)), _rectcircle.Y + _rectcircle.Width / 2 - (float)(_rectcircle.Width / 2 * Math.Cos(Math.Abs(CharAngle[i] - 270) * Math.PI / 180)));

                //Get total sweep angle with interval space
                fSweepAngle = (CharWidth[i] + _letterspace) * 360 / fCircleLength;
                StartAngle += fSweepAngle;
            }
        }

        /// <summary>
        /// Generate seal bitmap
        /// </summary>
        /// <returns></returns>
        public Bitmap TextOnPathBitmap()
        {
            // Create bitmap and graphics
            Bitmap bit = new Bitmap(_rect.Width, _rect.Height);
            Graphics g = Graphics.FromImage(bit);
            // Compute string length in graphics
            float[] fCharWidth = new float[_text.Length];
            float fTotalWidth = ComputeStringLength(_text, g, fCharWidth, _letterspace, _chardirect);

            // Compute arc's start-angle and end-angle
            double fStartAngle, fSweepAngle;
            fSweepAngle = fTotalWidth * 360 / (_rectcircle.Width * Math.PI);
            fStartAngle = 270 - fSweepAngle / 2;

            // Compute every character's position and angle
            PointF[] pntChars = new PointF[_text.Length];
            double[] fCharAngle = new double[_text.Length];
            ComputeCharPos(fCharWidth, pntChars, fCharAngle, fStartAngle);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            DrawSealBase(g);

            // Draw every character
            for (int i = 0; i < _text.Length; i++)
                DrawRotatedText(g, _text[i].ToString(), (float)(fCharAngle[i] + _degree), pntChars[i]);
            g.Dispose();
            // Return bitmap
            return bit;
        }

        /// <summary>
        /// Draw seal base 
        /// </summary>
        /// <param name="g"></param>
        /// 
        private void DrawSealBase(Graphics g)
        {
            // Draw background
            //快快透明
            //g.FillRectangle(Brushes.White, _rect);
            Pen pen1 = new Pen(Color.Red, 2);

            g.DrawArc(pen1, new Rectangle(1, 1, _rect.Width - 2, _rect.Height - 2), 0, 360);
            //g.FillEllipse(new SolidBrush(_fillcolor), new Rectangle(1, 1, _rect.Width - 2, _rect.Height - 2));
            //g.FillEllipse(Brushes.White, new Rectangle(4, 4, _rect.Width - 8, _rect.Height - 8));

            // Draw start signal
            StringFormat sf = new StringFormat();
            string strStar = "★";
            Font fnt = new Font(_font.FontFamily, _font.Size * 3);
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            SizeF siz = g.MeasureString(strStar, fnt);
            g.DrawString(strStar, fnt, new SolidBrush(_fillcolor), new RectangleF(_rect.Width / 2 - siz.Width / 2, _rect.Height / 2 - siz.Height / 2, siz.Width, siz.Height), sf);

            // Draw base string
            float[] fCharWidth = new float[_basestring.Length];
            float fTotalWidths = ComputeStringLength(_basestring, g, fCharWidth, 0, Char_Direction.Center);
            float fLeftPos = (_rect.Width - fTotalWidths) / 2;
            PointF pt;
            for (int i = 0; i < _basestring.Length; i++)
            {
                pt = new PointF(fLeftPos + fCharWidth[i] / 2, _rect.Height / 2 + siz.Height / 2 + 10);
                DrawRotatedText(g, _basestring[i].ToString(), 0, pt);
                fLeftPos += fCharWidth[i];
            }
        }



        /// <summary>
        /// Draw every rotated character
        /// </summary>
        /// <param name="g"></param>
        /// <param name="_text"></param>
        /// <param name="_angle"></param>
        /// <param name="_PointCenter"></param>
        private void DrawRotatedText(Graphics g, string _text, float _angle, PointF _PointCenter)
        {
            // Init format
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            // Create graphics path
            GraphicsPath gp = new GraphicsPath(System.Drawing.Drawing2D.FillMode.Winding);
            int x = (int)_PointCenter.X;
            int y = (int)_PointCenter.Y;

            // Add string
            gp.AddString(_text, _font.FontFamily, (int)_font.Style, _font.Size, new Point(x, y), sf);

            // Rotate string and draw it
            Matrix m = new Matrix();
            m.RotateAt(_angle, new PointF(x, y));
            g.Transform = m;
            g.DrawPath(new Pen(_color), gp);
            g.FillPath(new SolidBrush(_fillcolor), gp);
        }
    }

    public enum Char_Direction
    {
        Center = 0,
        OutSide = 1,
        ClockWise = 2,
        AntiClockWise = 3,
    }
    #endregion

    #region 图片水印

    /// <summary>
    /// 图片位置
    /// </summary>
    public enum ImagePosition
    {
        LeftTop,        //左上
        LeftBottom,    //左下
        RightTop,       //右上
        RigthBottom, //右下
        TopMiddle,     //顶部居中
        BottomMiddle, //底部居中
        Center           //中心
    }

    /// <summary>
    /// 水印图片的操作管理 Design by Gary Gong From Demetersoft.com
    /// </summary>
    public class WaterImageManage
    {
        /// <summary>
        /// 生成一个新的水印图片制作实例
        /// </summary>
        public WaterImageManage()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="sourcePicture">源图片文件名</param>
        /// <param name="waterImage">水印图片文件名</param>
        /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
        /// <param name="position">位置</param>
        /// <param name="PicturePath" >图片的路径</param>
        /// <returns>返回生成于指定文件夹下的水印文件名</returns>
        public Image DrawImage(string sourcePicture,
                                          string waterImage,
                                          float alpha,
                                          ImagePosition position,
                                          string PicturePath)
        {
            //
            // 判断参数是否有效
            //
            if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
            {
                return null;
            }

            //
            // 源图片，水印图片全路径
            //
            string sourcePictureName = PicturePath + sourcePicture;
            string waterPictureName = PicturePath + waterImage;
            string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
            string fileWaterExtension = System.IO.Path.GetExtension(waterPictureName).ToLower();
            //
            // 判断文件是否存在,以及类型是否正确
            //
            if (System.IO.File.Exists(sourcePictureName) == false ||
                System.IO.File.Exists(waterPictureName) == false || (
                fileSourceExtension != ".gif" &&
                fileSourceExtension != ".jpg" &&
                fileSourceExtension != ".png") || (
                fileWaterExtension != ".gif" &&
                fileWaterExtension != ".jpg" &&
                fileWaterExtension != ".png")
                )
            {
                return null;//sourcePicture;
            }

            //
            // 目标图片名称及全路径
            //
            string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg";

            //
            // 将需要加上水印的图片装载到Image对象中
            //
            Image imgPhoto = Image.FromFile(sourcePictureName);
            //
            // 确定其长宽
            //
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //
            // 封装 GDI+ 位图，此位图由图形图像及其属性的像素数据组成。
            //
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //
            // 设定分辨率
            // 
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 定义一个绘图画面用来装载位图
            //
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //
            //同样，由于水印是图片，我们也需要定义一个Image来装载它
            //
            Image imgWatermark = new Bitmap(waterPictureName);

            //
            // 获取水印图片的高度和宽度
            //
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //SmoothingMode：指定是否将平滑处理（消除锯齿）应用于直线、曲线和已填充区域的边缘。
            // 成员名称   说明 
            // AntiAlias      指定消除锯齿的呈现。 
            // Default        指定不消除锯齿。 
            // HighQuality 指定高质量、低速度呈现。 
            // HighSpeed   指定高速度、低质量呈现。 
            // Invalid        指定一个无效模式。 
            // None          指定不消除锯齿。 
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //
            // 第一次描绘，将我们的底图描绘在绘图画面上
            //
            grPhoto.DrawImage(imgPhoto,
                                        new Rectangle(0, 0, phWidth, phHeight),
                                        0,
                                        0,
                                        phWidth,
                                        phHeight,
                                        GraphicsUnit.Pixel);

            //
            // 与底图一样，我们需要一个位图来装载水印图片。并设定其分辨率
            //
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 继续，将水印图片装载到一个绘图画面grWatermark
            //
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //
            //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
            //       
            ImageAttributes imageAttributes = new ImageAttributes();

            //
            //Colormap: 定义转换颜色的映射
            //
            ColorMap colorMap = new ColorMap();

            //
            //我的水印图被定义成拥有绿色背景色的图片被替换成透明
            //
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = { 
           new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red红色
           new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green绿色
           new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue蓝色       
           new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //透明度     
           new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//

            // ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。
            // ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
             ColorAdjustType.Bitmap);

            //
            //上面设置完颜色，下面开始设置位置
            //
            int xPosOfWm;
            int yPosOfWm;

            switch (position)
            {
                case ImagePosition.BottomMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.Center:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = (phHeight - wmHeight) / 2;
                    break;
                case ImagePosition.LeftBottom:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    xPosOfWm = 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RightTop:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RigthBottom:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = 10;
                    break;
                default:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
            }

            //
            // 第二次绘图，把水印印上去
            //
            grWatermark.DrawImage(imgWatermark,
             new Rectangle(xPosOfWm,
                                 yPosOfWm,
                                 wmWidth,
                                 wmHeight),
                                 0,
                                 0,
                                 wmWidth,
                                 wmHeight,
                                 GraphicsUnit.Pixel,
                                 imageAttributes);


            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //
            // 保存文件到服务器的文件夹里面
            //
            //imgPhoto.Save(targetImage, ImageFormat.Jpeg);
            //imgPhoto.Dispose();
            //imgWatermark.Dispose();
            return imgPhoto;// targetImage.Replace(PicturePath, "");
        }
























        public Image DrawImage(string sourcePicture, Image waterImage, float alpha, ImagePosition position)
        {

            if (sourcePicture == string.Empty || waterImage == null || alpha == 0.0)
            {
                return null;
            }

            string sourcePictureName = sourcePicture;
            string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
            bool b = System.IO.File.Exists(sourcePictureName);
            if (!b)
            {
                return null;
            }
            b = (fileSourceExtension == ".gif" || fileSourceExtension == ".jpg" || fileSourceExtension == ".png");
            if (!b)
            {
                return null;
            }


            //
            // 将需要加上水印的图片装载到Image对象中
            //
            Image imgPhoto = Image.FromFile(sourcePictureName);

            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            Image imgWatermark = waterImage;// new Bitmap(waterImage);
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.DrawImage(imgPhoto,
                                        new Rectangle(0, 0, phWidth, phHeight),
                                        0,
                                        0,
                                        phWidth,
                                        phHeight,
                                        GraphicsUnit.Pixel);
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics grWatermark = Graphics.FromImage(bmWatermark);
            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
            float[][] colorMatrixElements = { 
           new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red红色
           new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green绿色
           new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue蓝色       
           new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //透明度     
           new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
             ColorAdjustType.Bitmap);
            int xPosOfWm;
            int yPosOfWm;
            switch (position)
            {
                case ImagePosition.BottomMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.Center:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = (phHeight - wmHeight) / 2;
                    break;
                case ImagePosition.LeftBottom:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    xPosOfWm = 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RightTop:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RigthBottom:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = 10;
                    break;
                default:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
            }
            grWatermark.DrawImage(imgWatermark,
             new Rectangle(xPosOfWm,
                                 yPosOfWm,
                                 wmWidth,
                                 wmHeight),
                                 0,
                                 0,
                                 wmWidth,
                                 wmHeight,
                                 GraphicsUnit.Pixel,
                                 imageAttributes);


            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();
            return imgPhoto;
        }
    }
    #endregion

}
